package cetcbigdata.da.service.hainan;

import cetcbigdata.da.base.Base;
import cetcbigdata.da.base.DownloadAndUploadMinio;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 政务公开
 * 一业一证清单
 */

public class YiYeYiZhengList extends Base {
    @Override
    public void getData(RecordSender recordSender, List<Object> fieldsList) {

    }

    @Override
    public JSONObject getDataDemo() {
        try {
            return this.parseListPage();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject parseListPage() {
        //当前页
        int currentPage = 1;
        //总页数
        int pages = 0;
        while (currentPage != pages){
            String listUrl = "https://wssp.hainan.gov.cn/wssp3/oneThingConditionInfo/getOnethingInfoPage?" +
                    "id=HZ2881f4424539dd0142453c856b0025&" +
                    "leaddept=&" +
                    "xzqhcode=&" +
                    "pageNumber="+currentPage+"&" +
                    "pageSize=10&" +
                    "onething=";
            JSONObject listHeader = new JSONObject();
            listHeader.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
            listHeader.put("Referer", "https://wssp.hainan.gov.cn/hnwt/oneindustry-onecertificate");
            JSONObject listParmas = new JSONObject();
            listParmas.put("id", "HZ2881f4424539dd0142453c856b0025");
            listParmas.put("leaddept", "");
            listParmas.put("xzqhcode", "");
            listParmas.put("pageNumber", currentPage);
            listParmas.put("pageSize", "10");
            listParmas.put("onething", "");
            String strResponse = postFormReq(listUrl,listHeader,listParmas);
            JSONObject response = JSONObject.parseObject(strResponse);
            for (Object o : response.getJSONObject("data").getJSONArray("datas")){
                JSONObject reqData = (JSONObject) o;
                String id  = reqData.getString("id");
                String pageUrl = "https://wssp.hainan.gov.cn/wssp3/yjs/dbznxq?";// + id;
                JSONObject pageHeader = new JSONObject();
                pageHeader.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
                pageHeader.put("Referer", "https://wssp.hainan.gov.cn/hnwt/oneThing?id=");
                JSONObject pageParmas = new JSONObject();
                pageParmas.put("id", id);

                String pageStrResponse;
                JSONObject result;
                try {
                    pageStrResponse = getReq(pageUrl,pageHeader,pageParmas);
                    JSONObject pageJSResponse = JSONObject.parseObject(pageStrResponse);
                    //==========获取详情页数据================
                    result = new JSONObject();
                    JSONObject pageDatas = pageJSResponse.getJSONObject("data").getJSONObject("datas");
                    JSONArray sxImplBasicMaterial = pageDatas.getJSONArray("sxImplBasicMaterial");
                    JSONArray sxList = pageDatas.getJSONArray("sxList");
                    JSONObject sxOnethingInfo = pageDatas.getJSONObject("sxOnethingInfo");
                    JSONArray sxOnethingQuestion = pageDatas.getJSONArray("sxOnethingQuestion");
                    //开头
                    result.put("名称", sxOnethingInfo.getString("basicname"));//完成
                    //地址
                    result.put("地址", "https://wssp.hainan.gov.cn/hnwt/oneThing?id=" + id);//完成
                    //联办效能
                    result.put("联办效能", getOtherInfoData(sxOnethingInfo));//完成
                    //基本信息
                    result.put("基本信息", getBasicInfoData(sxOnethingInfo));//完成
                    //申报须知
                    result.put("申报须知", sxOnethingInfo.getString("acceptcondition"));//完成
                    //办理流程
                    result.put("办理流程图", getFlowChart(id));//完成
                    //办理材料
                    result.put("办理材料", getBasicMaterData(sxImplBasicMaterial));//完成
                    //收费内容
                    result.put("收费内容", "无");//待确认
                    //办理结果
                    result.put("办理结果", getResultData(sxList));
                    //常见问题
                    result.put("常见问题", getQusetionData(sxOnethingQuestion));//完成

                } catch (Exception e) {
                    break;
                }
                System.out.println(currentPage+"\n"+result);//测试用代码
//                return processResult(
//                        null,
//                        null,
//                        null,
//                        pageStrResponse,
//                        result,
//                        "海南省",
//                        "政务公开-一业一证清单"
//                );
            }
            //更新当前页和总页数
            currentPage++;
            pages = response.getJSONObject("data").
                    getJSONObject("page").getInteger("pageCount") + 1;
        }
        return null;
    }

    //获取基本信息数据
    private JSONObject getBasicInfoData(JSONObject basicInfo){
        JSONObject result = new JSONObject();
        result.put("名称", basicInfo.getString("onething"));
        result.put("牵头部门", basicInfo.getString("leaddeptname"));
        result.put("行政区划", basicInfo.getString("onethingtemplateareaname"));

        if (null != basicInfo.getString("servertype")){
            StringBuilder servertypeResult = new StringBuilder();
            String servertype = basicInfo.getString("servertype");
            char[] servertypeArray = servertype.toCharArray();
            for (char i : servertypeArray){
                switch (i){
                    case '1':
                        servertypeResult.append("自然人");
                        break;
                    case '2':
                        servertypeResult.append("企业法人");
                        break;
                    case '3':
                        servertypeResult.append("事业法人");
                        break;
                    case '4':
                        servertypeResult.append("社会组织法人");
                        break;
                    case '5':
                        servertypeResult.append("非法人企业");
                        break;
                    case '6':
                        servertypeResult.append("行政机关");
                        break;
                    case '9':
                        servertypeResult.append("其他组织");
                        break;

                    default:
                        servertypeResult.append(";");

                }
            }
            result.put("服务对象",servertypeResult);
        }else {
            result.put("服务对象","无");
        }


        result.put("服务对象", isNotBlankOrNull(basicInfo.getString("servertype"))?
                basicInfo.getString("servertype") : "无");
        result.put("办理时间", basicInfo.getString("handletime"));
        result.put("线下跑动次数(次)", basicInfo.getString("offlineRunningTimes"));
        result.put("承诺办结时限(天)", basicInfo.getString("promiseday"));

        if (null !=  basicInfo.getString("isexpress")){
            result.put("是否支持物流快递",basicInfo.getString("isexpress").equals("1")?
                    "是" : "否");
        }else {
            result.put("是否支持物流快递","否");
        }

        switch (basicInfo.getString("isfee")){
            case "是":
                result.put("是否收费","是");
                break;
            case "否":
                result.put("是否收费","否");
                break;
            case "1":
                result.put("是否收费","是");
                break;
            default:
                result.put("是否收费","否");
        }

        result.put("主题编码", basicInfo.getString("onecode"));
        result.put("联办机构", basicInfo.getString("otherdept"));
        result.put("区划编码", basicInfo.getString("onethingtemplateareacode"));

        if (null != basicInfo.getString("handletype")){
            StringBuilder handletypeResult = new StringBuilder();
            String handletype = basicInfo.getString("handletype");
            char[] handletypeArray = handletype.toCharArray();
            for (char i : handletypeArray){
                switch (i){
                    case '1':
                        handletypeResult.append("窗口办理");
                        break;
                    case '2':
                        handletypeResult.append("网上办理");
                        break;
                    case '3':
                        handletypeResult.append("快递申请");
                        break;
                    default:
                        handletypeResult.append("、");

                }
            }
            result.put("办理形式", handletypeResult);
        }else {
            result.put("办理形式","无");
        }

        result.put("办理地址", basicInfo.getString("handleaddr"));
        result.put("需线下跑动原因", basicInfo.getString("offlineReason"));

        if (null !=  basicInfo.getString("isschedule")){
            result.put("是否支持预约办理",basicInfo.getString("isschedule").equals("1")?
                    "是" : "否");
        }else {
            result.put("是否支持预约办理","否");
        }

        if (null !=  basicInfo.getString("ispayonline")){
            result.put("是否支持网上支付",basicInfo.getString("ispayonline").equals("1")?
                    "是" : "否");
        }else {
            result.put("是否支持网上支付","否");
        }

        result.put("中介服务", basicInfo.getString("servicetype"));

        return result;
    }

    //获取办理流程图
    private JSONObject getFlowChart(String pageId){
        System.out.println("pageid:"+pageId);
        JSONObject fileResult = new JSONObject();
        String fileUrl = null;
        String minioId = null;
        try {
            fileUrl = "https://wssp.hainan.gov.cn/wssp3/yjs/bllc?id=" + pageId;
            minioId = fileDownloadAndUploadMinioGetImage(fileUrl, pageId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileResult.put("fileUrl",fileUrl);
        fileResult.put("minioId",minioId);

        return fileResult;
    }

    //获取办理材料数据
    private Object getBasicMaterData(JSONArray sxImplBasicMaterial) {
        if (null != sxImplBasicMaterial){
            JSONArray resultList = new JSONArray();
            for (Object o : sxImplBasicMaterial){
                JSONObject object = (JSONObject) o;
                JSONObject result = new JSONObject();

                //材料名称
                JSONObject materialname = new JSONObject();
                materialname.put("名称", object.getString("materialname"));
                if (null != object.getString("slybfileid") && object.getString("slybfileid").length() > 0){
                    String slybfileid = object.getString("slybfileid");
                    String emptyFileUrl = null;
                    String emptyFileMinioId = null;
                    JSONObject emptyFile = new JSONObject();
                    try {
                        emptyFileUrl = "https://wssp.hainan.gov.cn/hnwt/sx/download?" + "id=" + slybfileid;
                        emptyFileMinioId = fileDownloadAndUploadMinioGetImage("https://wssp.hainan.gov.cn/hnwt/sx/download?" + "id=" + slybfileid,
                                slybfileid);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    emptyFile.put("fileUrl", emptyFileUrl);
                    emptyFile.put("minioId", emptyFileMinioId);
                    materialname.put("空白表格", emptyFile);
                }

                if (null != object.getString("kbbgfileid") && object.getString("kbbgfileid").length() > 0) {
                    String kbbgfileid = object.getString("kbbgfileid");
                    String sampleFileUrl = null;
                    String sampleFileMinioId = null;
                    JSONObject sampleFile = new JSONObject();
                    try {
                        sampleFileUrl = "https://wssp.hainan.gov.cn/hnwt/sx/download?" + "id=" + kbbgfileid;
                        sampleFileMinioId = fileDownloadAndUploadMinioGetImage("https://wssp.hainan.gov.cn/hnwt/sx/download?" + "id=" + kbbgfileid,
                                kbbgfileid);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sampleFile.put("fileUrl", sampleFileUrl);
                    sampleFile.put("minioId", sampleFileMinioId);
                    materialname.put("示例详表", sampleFile);
                    result.put("材料名称", materialname);
                }

                //材料必要性
                switch (object.getString("isneed")) {
                    case "1":
                        result.put("材料必要性", "必要");
                        break;
                    case "2":
                        result.put("材料必要性", "非必要");
                        break;
                    case "3":
                        result.put("材料必要性", "容缺后补");
                        break;
                    default:
                        result.put("材料必要性", "无");
                }

                //材料要求
                JSONObject materialReq = new JSONObject();
                if (null != object.getString("materialformat")) {
                    switch (object.getString("materialformat")) {
                        case "1":
                            materialReq.put("形式", "纸质");
                            break;
                        case "2":
                            materialReq.put("形式", "电子");
                            break;
                        case "3":
                            materialReq.put("形式", "纸质和电子");
                            break;
                        case "4":
                            materialReq.put("形式", "纸质或电子");
                            break;
                        default:
                            materialReq.put("形式", "无");
                    }
                } else {
                    materialReq.put("形式", "无");
                }
                if (null != object.getString("materialtype")) {
                    switch (object.getString("materialtype")) {
                        case "1":
                            materialReq.put("类型", "原件");
                            break;
                        case "2":
                            materialReq.put("类型", "复印件");
                            break;
                        case "3":
                            materialReq.put("类型", "原件和复印件");
                            break;
                        default:
                            materialReq.put("类型", "无");
                    }
                } else {
                    materialReq.put("类型", "无");
                }
                materialReq.put("份数", object.getInteger("pagenum"));
                materialReq.put("规格", object.getString("pageformat"));
                materialReq.put("填报须知", object.getString("fillexplain"));
                result.put("材料要求",materialReq);

                //来源渠道
                if (null != object.getString("sourcetype")) {
                    switch (object.getString("sourcetype")) {
                        case "10":
                            result.put("来源渠道", "申请人自备");
                            break;
                        case "20":
                            result.put("来源渠道", "政府部门核发");
                            break;
                        case "99":
                            result.put("来源渠道", "其他");
                            break;
                        default:
                            result.put("来源渠道", "其他");
                    }
                } else {
                    result.put("来源渠道", "其他");
                }

                //其他信息
                JSONObject materialOther = new JSONObject();
                materialOther.put("要求提供材料依据", object.getString("bylaw"));
                materialOther.put("受理标准", object.getString("acceptstand"));
                materialOther.put("来源渠道说明", object.getString("sourceexplain"));
                result.put("其他信息", materialOther);

                resultList.add(result);
            }
            return resultList;
        }
        return "无";
    }

    //获取办理结果数据
    private Object getResultData(JSONArray sxList) {
        if (null != sxList){
            JSONArray resultList = new JSONArray();
            for (Object o : sxList){
                JSONObject object = (JSONObject) o;
                JSONObject result = new JSONObject();
                result.put("事项", object.getString("taskname"));
                result.put("业务部门", object.getString("otherdept"));
                result.put("办理结果", object.getString("resultname"));

                JSONObject guide = new JSONObject();
                String sourcekey = object.getString("sourcekey");
                String id = String.valueOf(object.getInteger("id"));
                String guideUrl = "https://wssp.hainan.gov.cn/wssp3/bszn/exempt/allInfo";
                JSONObject guideHeader = new JSONObject();
                guideHeader.put("Referer", "https://wssp.hainan.gov.cn/hnwt/handlingGuideline?id="+id+"&sourcekey="+sourcekey);
                JSONObject guideParmas = new JSONObject();
                guideParmas.put("id",sourcekey);
                guideParmas.put("type", "1");
                guide.put("指南id", id);
                guide.put("指南url", guideUrl);
                guide.put("指南header" ,guideHeader);
                guide.put("指南parmas" ,guideParmas);
                result.put("办事指南", guide);

                result.put("备注", object.getString("remark"));

                resultList.add(result);
            }
            return resultList;
        }
        return "无";
    }

    //获取联办效能数据
    private JSONObject getOtherInfoData(JSONObject sxOnethingInfo) {
        JSONObject result = new JSONObject();
        JSONObject date = new JSONObject();
        date.put("分开办", (isNotBlankOrNull(sxOnethingInfo.getString("oldpromiseday"))?
                sxOnethingInfo.getString("oldpromiseday") : "0") + "天");
        date.put("一次办", isNotBlankOrNull(sxOnethingInfo.getString("promiseday"))?
                "最多" + sxOnethingInfo.getString("promiseday") + "个工作日" : "未知");

        JSONObject times = new JSONObject();
        times.put("分开办", (isNotBlankOrNull(sxOnethingInfo.getString("oldofflineRunningTimes"))?
                sxOnethingInfo.getString("oldofflineRunningTimes") : "0") + "次");
        times.put("一次办", "最多" + (isNotBlankOrNull(sxOnethingInfo.getString("offlineRunningTimes"))?
                sxOnethingInfo.getString("offlineRunningTimes") : "0次") + "次");

        JSONObject materials = new JSONObject();
        materials.put("分开办", (isNotBlankOrNull(sxOnethingInfo.getString("oldmaterialnum"))?
                sxOnethingInfo.getString("oldmaterialnum") : "0") + "份");
        materials.put("一次办", (isNotBlankOrNull(sxOnethingInfo.getString("materialnum"))?
                sxOnethingInfo.getString("materialnum") : "0") + "份");

        JSONObject steps = new JSONObject();
        steps.put("分开办", (isNotBlankOrNull(sxOnethingInfo.getString("oldstepnum"))?
                sxOnethingInfo.getString("oldstepnum") : "0") + "次");
        steps.put("一次办", (isNotBlankOrNull(sxOnethingInfo.getString("stepnum"))?
                sxOnethingInfo.getString("stepnum") : "0次") + "次");

        result.put("办理时间",date);
        result.put("跑动次数",times);
        result.put("递交材料",materials);
        result.put("办理环节",steps);

        return result;
    }

    //获取常见问题数据
    private Object getQusetionData(JSONArray sxOnethingQuestion) {
        JSONArray resultList = new JSONArray();
        if(null != sxOnethingQuestion){
            for (Object o : sxOnethingQuestion){
                JSONObject object = (JSONObject) o;
                JSONObject result = new JSONObject();
                result.put("问题", object.getString("question"));
                result.put("答案", object.getString("answer"));
                resultList.add(result);
            }
            return resultList;
        }
        return "无";
    }

    public static String fileDownloadAndUploadMinioGetImage(String url, String fileName ) throws Exception {
        JSONObject param = new JSONObject();
        JSONObject headers = new JSONObject();
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");

        //=========================================================测试性注释以下代码===============================================================
        return DownloadAndUploadMinio.getInstance().downloadGet(
                url,
                headers,
                param,
                fileName
        );
//        return null;
    }

    public static void main(String[] args) {
        YiYeYiZhengList yiYeYiZhengList = new YiYeYiZhengList();
        yiYeYiZhengList.getDataDemo();
    }
}
